import Vuex from "vuex"
import Vue from "vue"

Vue.use(Vuex)

const state = {
  cart_goods: []
}

const mutations = {
  add_cart(state, cart) {
    state.cart_goods.push(cart)
  },
  add_count(state, index) {
    state.cart_goods[index].count += 1
  },

  changefalse(state, index) {
    state.cart_goods[index].ischebox = false
  },
  changetrue(state, index) {
    state.cart_goods[index].ischebox = true
  },
  //把所有的按钮都设置为false或ture
  all(state, objec) {
    state.cart_goods[objec.index].ischebox = objec.checked
  }
}

const actions = {
  iscart(context, cart) {
    let indey = 0
    const flog = context.state.cart_goods.filter((item, index) => {
      if (item.iid === cart.iid) {
        indey = index
        return item.iid === cart.iid
      }
    })

    if (flog.length !== 0) {
      context.commit("add_count", indey)
    } else {
      context.commit("add_cart", cart)
    }
  },

  isture(context, index) {
    if (context.state.cart_goods[index].ischebox) {
      context.commit('changefalse', index)
    } else {
      context.commit('changetrue', index)
    }

  },
  //把所有的按钮都设置为false或ture
  all_checked(context, checked) {
    context.state.cart_goods.forEach((item, index) => {
      context.commit('all', {
        checked,
        index
      })
    });
  }
}

const store = new Vuex.Store({
  state,
  mutations,
  actions
})

export default store